/**
 * 设置相关Mock数据
 */

import { generateId } from '../utils'

// 模拟用户设置数据
const mockUserSettings = {
  id: generateId(),
  userId: 'user_001',
  // 通用设置
  general: {
    language: 'zh-CN', // 语言设置
    theme: 'auto', // 主题：light, dark, auto
    fontSize: 'medium', // 字体大小：small, medium, large
    startOfWeek: 1, // 一周开始：0=周日, 1=周一
    dateFormat: 'YYYY-MM-DD', // 日期格式
    timeFormat: '24h', // 时间格式：12h, 24h
    currency: 'CNY', // 货币单位
    timezone: 'Asia/Shanghai' // 时区
  },
  
  // 通知设置
  notifications: {
    enabled: true, // 是否启用通知
    sound: true, // 声音提醒
    vibration: true, // 震动提醒
    badge: true, // 角标提醒
    
    // 习惯提醒
    habits: {
      enabled: true,
      time: '09:00', // 提醒时间
      frequency: 'daily', // 提醒频率：daily, weekly
      sound: 'default'
    },
    
    // 待办提醒
    todos: {
      enabled: true,
      beforeDue: 30, // 截止前多少分钟提醒
      overdue: true, // 逾期提醒
      sound: 'default'
    },
    
    // 财务提醒
    finance: {
      enabled: true,
      budgetWarning: 80, // 预算警告百分比
      dailyReport: true, // 每日报告
      weeklyReport: true, // 周报告
      sound: 'default'
    },
    
    // 时间提醒
    time: {
      enabled: true,
      breakReminder: true, // 休息提醒
      breakInterval: 60, // 休息间隔（分钟）
      focusReminder: true, // 专注提醒
      sound: 'default'
    }
  },
  
  // 隐私设置
  privacy: {
    dataCollection: true, // 数据收集
    analytics: true, // 分析统计
    crashReports: true, // 崩溃报告
    locationServices: false, // 位置服务
    biometricAuth: false, // 生物识别认证
    autoLock: true, // 自动锁定
    lockTimeout: 300 // 锁定超时（秒）
  },
  
  // 同步设置
  sync: {
    enabled: true, // 是否启用同步
    autoSync: true, // 自动同步
    syncInterval: 'realtime', // 同步间隔：realtime, hourly, daily
    wifiOnly: true, // 仅WiFi同步
    
    // 同步内容
    content: {
      habits: true,
      todos: true,
      finance: true,
      time: true,
      settings: true
    }
  },
  
  // 备份设置
  backup: {
    enabled: true, // 是否启用备份
    autoBackup: true, // 自动备份
    backupInterval: 'weekly', // 备份间隔：daily, weekly, monthly
    maxBackups: 10, // 最大备份数量
    includeMedia: false, // 包含媒体文件
    cloudProvider: 'icloud' // 云服务提供商：icloud, google, dropbox
  },
  
  // 显示设置
  display: {
    showCompletedHabits: true, // 显示已完成习惯
    showCompletedTodos: false, // 显示已完成待办
    compactMode: false, // 紧凑模式
    showStatistics: true, // 显示统计信息
    showProgress: true, // 显示进度
    animationsEnabled: true, // 启用动画
    hapticFeedback: true // 触觉反馈
  },
  
  // 高级设置
  advanced: {
    debugMode: false, // 调试模式
    betaFeatures: false, // 测试功能
    dataExport: true, // 数据导出
    dataImport: true, // 数据导入
    resetWarnings: true, // 重置警告
    developerOptions: false // 开发者选项
  },
  
  createdAt: '2024-01-01T00:00:00.000Z',
  updatedAt: new Date().toISOString()
}

// 模拟应用设置
const mockAppSettings = {
  version: '1.0.0',
  buildNumber: '100',
  environment: 'production',
  apiVersion: 'v1',
  features: {
    habits: true,
    todos: true,
    finance: true,
    time: true,
    statistics: true,
    social: false,
    premium: false
  },
  limits: {
    maxHabits: 50,
    maxTodos: 200,
    maxCategories: 20,
    maxTags: 50,
    maxBackups: 10
  },
  maintenance: {
    enabled: false,
    message: '',
    startTime: null,
    endTime: null
  }
}

// 模拟通知历史
const mockNotificationHistory = [
  {
    id: generateId(),
    type: 'habit_reminder',
    title: '习惯提醒',
    message: '该完成今天的运动习惯了！',
    data: { habitId: 'habit_001' },
    read: false,
    createdAt: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString() // 2小时前
  },
  {
    id: generateId(),
    type: 'todo_due',
    title: '待办提醒',
    message: '任务"完成项目报告"即将到期',
    data: { todoId: 'todo_001' },
    read: true,
    createdAt: new Date(Date.now() - 4 * 60 * 60 * 1000).toISOString() // 4小时前
  },
  {
    id: generateId(),
    type: 'budget_warning',
    title: '预算警告',
    message: '本月餐饮支出已超过预算的80%',
    data: { category: '餐饮', percentage: 85 },
    read: true,
    createdAt: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString() // 1天前
  }
]

export default {
  // 获取用户设置
  'GET /settings/user': async () => {
    return mockUserSettings
  },
  
  // 更新用户设置
  'PUT /settings/user': async (data) => {
    const allowedSections = ['general', 'notifications', 'privacy', 'sync', 'backup', 'display', 'advanced']
    const updates = {}
    
    allowedSections.forEach(section => {
      if (data[section]) {
        updates[section] = {
          ...mockUserSettings[section],
          ...data[section]
        }
      }
    })
    
    Object.assign(mockUserSettings, updates, {
      updatedAt: new Date().toISOString()
    })
    
    return mockUserSettings
  },
  
  // 重置用户设置
  'POST /settings/user/reset': async (data) => {
    const { section } = data
    
    if (!section) {
      throw new Error(JSON.stringify({ code: 1001, message: '请指定要重置的设置部分' }))
    }
    
    const defaultSettings = {
      general: {
        language: 'zh-CN',
        theme: 'auto',
        fontSize: 'medium',
        startOfWeek: 1,
        dateFormat: 'YYYY-MM-DD',
        timeFormat: '24h',
        currency: 'CNY',
        timezone: 'Asia/Shanghai'
      },
      notifications: {
        enabled: true,
        sound: true,
        vibration: true,
        badge: true,
        habits: {
          enabled: true,
          time: '09:00',
          frequency: 'daily',
          sound: 'default'
        },
        todos: {
          enabled: true,
          beforeDue: 30,
          overdue: true,
          sound: 'default'
        },
        finance: {
          enabled: true,
          budgetWarning: 80,
          dailyReport: true,
          weeklyReport: true,
          sound: 'default'
        },
        time: {
          enabled: true,
          breakReminder: true,
          breakInterval: 60,
          focusReminder: true,
          sound: 'default'
        }
      },
      privacy: {
        dataCollection: true,
        analytics: true,
        crashReports: true,
        locationServices: false,
        biometricAuth: false,
        autoLock: true,
        lockTimeout: 300
      },
      sync: {
        enabled: true,
        autoSync: true,
        syncInterval: 'realtime',
        wifiOnly: true,
        content: {
          habits: true,
          todos: true,
          finance: true,
          time: true,
          settings: true
        }
      },
      backup: {
        enabled: true,
        autoBackup: true,
        backupInterval: 'weekly',
        maxBackups: 10,
        includeMedia: false,
        cloudProvider: 'icloud'
      },
      display: {
        showCompletedHabits: true,
        showCompletedTodos: false,
        compactMode: false,
        showStatistics: true,
        showProgress: true,
        animationsEnabled: true,
        hapticFeedback: true
      },
      advanced: {
        debugMode: false,
        betaFeatures: false,
        dataExport: true,
        dataImport: true,
        resetWarnings: true,
        developerOptions: false
      }
    }
    
    if (section === 'all') {
      Object.assign(mockUserSettings, defaultSettings, {
        updatedAt: new Date().toISOString()
      })
    } else if (defaultSettings[section]) {
      mockUserSettings[section] = defaultSettings[section]
      mockUserSettings.updatedAt = new Date().toISOString()
    } else {
      throw new Error(JSON.stringify({ code: 1001, message: '无效的设置部分' }))
    }
    
    return { message: '设置重置成功' }
  },
  
  // 获取应用设置
  'GET /settings/app': async () => {
    return mockAppSettings
  },
  
  // 获取通知历史
  'GET /settings/notifications/history': async (params = {}) => {
    const { page = 1, pageSize = 20, type, read } = params
    
    let filteredNotifications = [...mockNotificationHistory]
    
    // 按类型筛选
    if (type) {
      filteredNotifications = filteredNotifications.filter(notification => notification.type === type)
    }
    
    // 按已读状态筛选
    if (read !== undefined) {
      filteredNotifications = filteredNotifications.filter(notification => notification.read === read)
    }
    
    // 分页
    const startIndex = (page - 1) * pageSize
    const endIndex = startIndex + pageSize
    const paginatedNotifications = filteredNotifications.slice(startIndex, endIndex)
    
    return {
      data: paginatedNotifications,
      pagination: {
        page,
        pageSize,
        total: filteredNotifications.length,
        totalPages: Math.ceil(filteredNotifications.length / pageSize)
      }
    }
  },
  
  // 标记通知为已读
  'PUT /settings/notifications/:id/read': async (data, { pathParams }) => {
    const { id } = pathParams
    const notification = mockNotificationHistory.find(n => n.id === id)
    
    if (!notification) {
      throw new Error(JSON.stringify({ code: 1003, message: '通知不存在' }))
    }
    
    notification.read = true
    
    return { message: '标记成功' }
  },
  
  // 批量标记通知为已读
  'POST /settings/notifications/mark-read': async (data) => {
    const { ids, all } = data
    
    if (all) {
      mockNotificationHistory.forEach(notification => {
        notification.read = true
      })
    } else if (ids && Array.isArray(ids)) {
      ids.forEach(id => {
        const notification = mockNotificationHistory.find(n => n.id === id)
        if (notification) {
          notification.read = true
        }
      })
    }
    
    return { message: '标记成功' }
  },
  
  // 清除通知历史
  'DELETE /settings/notifications/history': async (data) => {
    const { ids, all, olderThan } = data
    
    if (all) {
      mockNotificationHistory.length = 0
    } else if (ids && Array.isArray(ids)) {
      ids.forEach(id => {
        const index = mockNotificationHistory.findIndex(n => n.id === id)
        if (index !== -1) {
          mockNotificationHistory.splice(index, 1)
        }
      })
    } else if (olderThan) {
      const cutoffDate = new Date(olderThan)
      for (let i = mockNotificationHistory.length - 1; i >= 0; i--) {
        if (new Date(mockNotificationHistory[i].createdAt) < cutoffDate) {
          mockNotificationHistory.splice(i, 1)
        }
      }
    }
    
    return { message: '清除成功' }
  },
  
  // 测试通知
  'POST /settings/notifications/test': async (data) => {
    const { type = 'test' } = data
    
    const testNotification = {
      id: generateId(),
      type,
      title: '测试通知',
      message: '这是一条测试通知消息',
      data: {},
      read: false,
      createdAt: new Date().toISOString()
    }
    
    mockNotificationHistory.unshift(testNotification)
    
    return {
      message: '测试通知已发送',
      notification: testNotification
    }
  },
  
  // 导出数据
  'POST /settings/data/export': async (data) => {
    const { format = 'json', modules = ['all'] } = data
    
    if (!['json', 'csv', 'xlsx'].includes(format)) {
      throw new Error(JSON.stringify({ code: 1001, message: '不支持的导出格式' }))
    }
    
    // 模拟导出过程
    const exportData = {
      exportId: generateId(),
      format,
      modules,
      status: 'processing',
      progress: 0,
      createdAt: new Date().toISOString(),
      estimatedTime: 30 // 秒
    }
    
    // 模拟异步处理
    setTimeout(() => {
      exportData.status = 'completed'
      exportData.progress = 100
      exportData.downloadUrl = `https://api.example.com/downloads/${exportData.exportId}.${format}`
      exportData.completedAt = new Date().toISOString()
    }, 3000)
    
    return exportData
  },
  
  // 获取导出状态
  'GET /settings/data/export/:id': async (params, { pathParams }) => {
    const { id } = pathParams
    
    // 模拟导出状态
    return {
      exportId: id,
      status: 'completed',
      progress: 100,
      downloadUrl: `https://api.example.com/downloads/${id}.json`,
      createdAt: new Date(Date.now() - 5 * 60 * 1000).toISOString(),
      completedAt: new Date().toISOString()
    }
  },
  
  // 导入数据
  'POST /settings/data/import': async (data) => {
    const { file, format = 'json', overwrite = false } = data
    
    if (!file) {
      throw new Error(JSON.stringify({ code: 1001, message: '请选择要导入的文件' }))
    }
    
    // 模拟导入过程
    const importData = {
      importId: generateId(),
      filename: file.name || 'import.json',
      format,
      overwrite,
      status: 'processing',
      progress: 0,
      createdAt: new Date().toISOString(),
      estimatedTime: 60 // 秒
    }
    
    // 模拟异步处理
    setTimeout(() => {
      importData.status = 'completed'
      importData.progress = 100
      importData.result = {
        imported: {
          habits: 15,
          todos: 32,
          finance: 128,
          time: 45
        },
        skipped: {
          habits: 2,
          todos: 1,
          finance: 5,
          time: 0
        },
        errors: []
      }
      importData.completedAt = new Date().toISOString()
    }, 5000)
    
    return importData
  },
  
  // 获取导入状态
  'GET /settings/data/import/:id': async (params, { pathParams }) => {
    const { id } = pathParams
    
    // 模拟导入状态
    return {
      importId: id,
      status: 'completed',
      progress: 100,
      result: {
        imported: {
          habits: 15,
          todos: 32,
          finance: 128,
          time: 45
        },
        skipped: {
          habits: 2,
          todos: 1,
          finance: 5,
          time: 0
        },
        errors: []
      },
      createdAt: new Date(Date.now() - 10 * 60 * 1000).toISOString(),
      completedAt: new Date(Date.now() - 5 * 60 * 1000).toISOString()
    }
  },
  
  // 清除应用数据
  'POST /settings/data/clear': async (data) => {
    const { modules = [], confirm = false } = data
    
    if (!confirm) {
      throw new Error(JSON.stringify({ code: 1001, message: '请确认清除操作' }))
    }
    
    if (modules.length === 0) {
      throw new Error(JSON.stringify({ code: 1001, message: '请选择要清除的数据模块' }))
    }
    
    // 模拟清除过程
    const result = {
      cleared: {},
      errors: []
    }
    
    modules.forEach(module => {
      switch (module) {
        case 'habits':
          result.cleared.habits = 25
          break
        case 'todos':
          result.cleared.todos = 48
          break
        case 'finance':
          result.cleared.finance = 156
          break
        case 'time':
          result.cleared.time = 89
          break
        case 'settings':
          result.cleared.settings = 1
          break
        default:
          result.errors.push(`未知模块: ${module}`)
      }
    })
    
    return {
      message: '数据清除完成',
      result
    }
  },
  
  // 获取存储使用情况
  'GET /settings/storage': async () => {
    return {
      total: 1024 * 1024 * 100, // 100MB
      used: 1024 * 1024 * 25, // 25MB
      available: 1024 * 1024 * 75, // 75MB
      breakdown: {
        habits: 1024 * 1024 * 5, // 5MB
        todos: 1024 * 1024 * 8, // 8MB
        finance: 1024 * 1024 * 7, // 7MB
        time: 1024 * 1024 * 3, // 3MB
        media: 1024 * 1024 * 2, // 2MB
        cache: 1024 * 1024 * 0 // 0MB
      }
    }
  },
  
  // 清理缓存
  'POST /settings/storage/clear-cache': async () => {
    return {
      message: '缓存清理完成',
      freedSpace: 1024 * 1024 * 15 // 15MB
    }
  },
  
  // 获取应用信息
  'GET /settings/about': async () => {
    return {
      appName: 'TicTac',
      version: '1.0.0',
      buildNumber: '100',
      buildDate: '2024-01-01',
      developer: 'TicTac Team',
      website: 'https://tictac.app',
      support: 'support@tictac.app',
      privacy: 'https://tictac.app/privacy',
      terms: 'https://tictac.app/terms',
      licenses: [
        {
          name: 'Vue.js',
          version: '3.3.0',
          license: 'MIT',
          url: 'https://github.com/vuejs/core'
        },
        {
          name: 'uni-app',
          version: '3.0.0',
          license: 'Apache-2.0',
          url: 'https://github.com/dcloudio/uni-app'
        }
      ]
    }
  }
}